import threading
from math import floor

fitnessTotal = 0

class MyThread( threading.Thread ):
	def __init__(self,grid,offset,height):
		threading.Thread.__init__(self)
		self.grid = grid
		self.offset = offset
		self.height = height
	def run(self):
		global fitnessTotal, refGrid, wrange
		myTotal = 0
		for h in range(0,self.height):
			for w in range(0,wrange):
				myTotal += abs(self.grid[h][w] - refGrid[h+self.offset][w])
		fitnessTotal += myTotal

#don't go much above hrange*wrange = 10^6
#no, really, don't
hrange = 1000
wrange = 1000

threads = []
numThreads = 5
my_arr = [[0]*wrange]*hrange
refGrid = [[0]*wrange]*hrange


#build a ref grid
for h in range(0,hrange):
	refGrid[h] = [0]*wrange
	for w in range(0,wrange):
		refGrid[h][w] = (h * wrange ) + w

#build an image (ie child)
for h in range(0,hrange):
	my_arr[h] = [0]*wrange
	for w in range(0,wrange):
		my_arr[h][w] = (h * wrange ) + w + 1

#print refGrid
#print my_arr
print 'images made'

raw_part = 1.0*len(my_arr)/numThreads
part = int(floor(raw_part))

if part == 0:
	print 'you cannot have more threads than rows!'

if part != raw_part:
	numThreads += 1

print 'numThreads:',numThreads

for i in range(0,numThreads):
	start = i * part
	end = (i+1)*part
	# Create new threads
	threads.append(MyThread(my_arr[start:end], start, part))

print 'starting threads'

for t in threads:
	t.start()

#print threading.enumerate()

for t in threads:
	while t.isAlive():
		t.join()

#print threading.enumerate()

print fitnessTotal
